package cn.stylefeng.guns.modular.rm;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Iterator;

@RestController
@RequestMapping("cp")
public class HttpController {

    @RequestMapping("httpJSON")
    public JSONObject httpJSON(@RequestBody(required = false) JSONObject requestBody) {
        return JSONObject.parseObject(httpStr(requestBody));
    }

    @RequestMapping("httpStr")
    public String httpStr(@RequestBody(required = false) JSONObject requestBody) {
        String url = requestBody.getString("url");
        String method = requestBody.getString("method");
        JSONObject header = requestBody.getJSONObject("header");

        HttpRequest request = null;
        if ("get".equals(method)) {
            request = HttpUtil.createGet(url);
        } else {
            request = HttpUtil.createPost(url);
        }

        if (header != null) {
            Iterator<String> iterator = header.keySet().iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                request.header(key, header.getString(key));
            }
        }

        JSONObject body = requestBody.getJSONObject("body");
        if (body != null) {
            request.body(body.toJSONString());
        }
        String res = request.execute().body();
        return res;
    }
}
